package com.example.dbsample.config.apollo;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.example.dbsample.context.ThreadLocalContext;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.Assert;

import java.util.Map;

@Slf4j
public class AdminApolloConfig {
    private static Config apollpoConfig = ConfigService.getConfig("admin");
    private static Config applicationApolloConfig = ConfigService.getConfig("application");

    private static final String UIDP_ADMIN_HOST = "uidp.%s.host.url";
    private static final String KEY_HOST_URL = "%s.%s.host.url";

    /**
     * 根据业务线获取uidp admin host
     * @param businessLineCode
     * @return
     */
    public static String getUidpAdminHost(String businessLineCode) {
        businessLineCode = StringUtils.defaultString(businessLineCode.toLowerCase(), "cldx");
        String key = String.format(UIDP_ADMIN_HOST, businessLineCode);
        return apollpoConfig.getProperty(key, "");
    }

    public static String getHostByAppName(String appName) {
        Assert.isTrue(StringUtils.isNotBlank(appName), "入参appName不能为空");
        String businessLine = ThreadLocalContext.getBusinessLine();
        businessLine = StringUtils.defaultString(businessLine, "cldx").toLowerCase();
        String key = String.format(KEY_HOST_URL, appName.toLowerCase(), businessLine);
        return apollpoConfig.getProperty(key, "");
    }

    public static String getAppId(String businessLineCode) {
        String channelEnum = applicationApolloConfig.getProperty("sample.app.channel.enum", "");
        Map<String, String> enumList = new Gson().fromJson(channelEnum, Map.class);
        String appId = enumList.get(StringUtils.upperCase(businessLineCode));
        return appId == null ? "100" : appId;
    }

    // TODO 下面待补充
}
